use crate::{
    auth::AuthService,
    AppError, AppResult, LoginRequest, LoginResponse, User,
};
use tauri::State;
use crate::AppState;

#[tauri::command]
pub async fn login(request: LoginRequest) -> AppResult<LoginResponse> {
    // 验证用户凭据
    let user = AuthService::verify_credentials(&request.username, &request.password)?;
    
    // 生成JWT token
    let token = AuthService::generate_token(&user)?;
    
    // 更新最后登录时间
    AuthService::update_last_login_time(&user.id)?;
    
    // 返回登录响应
    Ok(LoginResponse {
        token,
        user: user.clone(),
        permissions: vec![
            "system:user:list".to_string(),
            "system:user:add".to_string(),
            "system:user:edit".to_string(),
            "system:user:delete".to_string(),
            "sip:call:list".to_string(),
            "sip:call:make".to_string(),
            "sip:call:hangup".to_string(),
            "monitor:online:list".to_string(),
            "monitor:job:list".to_string(),
        ],
    })
}

#[tauri::command]
pub async fn logout(state: State<'_, AppState>) -> AppResult<()> {
    if let Some(user) = &state.current_user {
        AuthService::logout(&user.id)?;
    }
    
    Ok(())
}

#[tauri::command]
pub async fn get_current_user(state: State<'_, AppState>) -> AppResult<Option<User>> {
    Ok(state.current_user.clone())
}

#[tauri::command]
pub async fn verify_token(token: String) -> AppResult<User> {
    AuthService::verify_token(&token)
}
